package com.example.videotest;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.*;
import android.view.SurfaceHolder.Callback;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener{
	private Camera mCamera;
	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
	private Button startButton;
	private boolean mIsRecording = false;
	private MediaRecorder mediaRecorder;
	private File dir;
	private File myRecAudioFile;
	private String SD_CARD_TEMP_DIR = getSDPath() + File.separator + "XueYinYue"
			+ File.separator;
	private Camera.AutoFocusCallback myAutoFocusCallback = null;
	private int result;//相机旋转角度
	private int width;//屏幕宽度
	private int height;//屏幕高度
	private float density;
	private int densityDpi;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mSurfaceView = (SurfaceView)findViewById(R.id.surfaceview);
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		dir = new File(SD_CARD_TEMP_DIR);
		if (!dir.exists()) {
			dir.mkdir();//若文件夹不存在创建文件夹
		}


		mSurfaceHolder.addCallback(new Callback() {
			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				releaseCamera();
			}
			
			@Override
			public void surfaceCreated(SurfaceHolder holder) {

				initpreview();
			}
			
			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width,
					int height) {
				
			}
		});
		startButton = (Button)findViewById(R.id.start);
		startButton.setOnClickListener(this);
		myAutoFocusCallback = new Camera.AutoFocusCallback() {

			public void onAutoFocus(boolean success, Camera camera) {

				if(success){
					mCamera.setOneShotPreviewCallback(null);
					Toast.makeText(MainActivity.this,
							"自动聚焦成功", Toast.LENGTH_SHORT).show();
				}else {
					Toast.makeText(MainActivity.this,
							"自动聚焦失败", Toast.LENGTH_SHORT).show();
				}

			}
		};

		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		width= metric.widthPixels;  // 屏幕宽度（像素）
		height = metric.heightPixels;  // 屏幕高度（像素）
		Log.d("---width----",width+"");
		Log.d("---height----",height+"");
		//density = metric.density;  // 屏幕密度（0.75 / 1.0 / 1.5）
//		densityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）
	}

	protected void releaseCamera() {
		if(mCamera!=null){
			mCamera.lock();//摄像头上锁
			mCamera.stopPreview();//停止摄像头预览
			mCamera.release();
			mCamera = null;
		}
	}



	protected void initpreview() {
		if(mCamera!=null){

			mCamera=null;
			Log.d("--mcamera--","isnull");
		}
		mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK);//CAMERA_FACING_FRONT前置摄像头,CAMERA_FACING_BACK后置摄像头
		try {
			mCamera.setPreviewDisplay(mSurfaceHolder);
		} catch (IOException e) {

			e.printStackTrace();
		}
		setCameraDisplayOrientation(this,CameraInfo.CAMERA_FACING_BACK,mCamera);
		mCamera.startPreview();//启动相机预览

	}
	//你好啊
	public void setCameraDisplayOrientation(Activity activity,
												   int cameraId, android.hardware.Camera camera) {
		     android.hardware.Camera.CameraInfo info =
		             new android.hardware.Camera.CameraInfo();
		     android.hardware.Camera.getCameraInfo(cameraId, info);
		     int rotation = activity.getWindowManager().getDefaultDisplay()
				           .getRotation();
		     int degrees = 0;
		     switch (rotation) {
				 case Surface.ROTATION_0: degrees = 0; break;
				 case Surface.ROTATION_90: degrees = 90; break;
				 case Surface.ROTATION_180: degrees = 180; break;
				 case Surface.ROTATION_270: degrees = 270; break;
			 }


		     if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
				 result = (info.orientation + degrees) % 360;
				 result = (360 - result) % 360;  // compensate the mirror
				 Log.d("-----------result---------------",result+"");
			 } else {  // back-facing
				 result = (info.orientation - degrees + 360) % 360;
				 Log.d("-----------result---------------",result+"");
			 }
		camera.setDisplayOrientation(result);

	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onClick(View view) {
		int id = view.getId();
		switch (id) {
		case R.id.start:

			if(mIsRecording==false) {
				mIsRecording=true;
				recorder();
				Log.d("URL",SD_CARD_TEMP_DIR);
			}else{
				stopmediaRecorder();
				finish();
			}
			if(mIsRecording){
				startButton.setText("stop");
				mIsRecording = true;
			}else {
				startButton.setText("start");
				mIsRecording = false;
			}
			break;
		default:
			break;
		}

	}

	private void stopmediaRecorder() {
		if(mediaRecorder!=null){
			if(mIsRecording){


				mediaRecorder.stop();
				mediaRecorder.release();
				mediaRecorder = null;
				releaseCamera();
			}
		}
	}





	public static String getSDPath() {//获取sd卡路径
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();
		} else {
			return null;
		}

		return sdDir.toString();

	}

	public void recorder() {
		try {

			mCamera.unlock();//解锁相机允许另一个进程访问它
			mediaRecorder = new MediaRecorder();
			mediaRecorder.reset();//mediarecorder重启其空闲状态.在调用
			myRecAudioFile = File.createTempFile("video", ".mp4", dir);
			mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
			mediaRecorder.setCamera(mCamera);
			mediaRecorder.setMaxDuration(10000000);//设置视屏最长时间单位ms
			mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 音麦
			mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);// 视频源
			mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);// 输出格式
			mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);// 声音源码
			mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);// 视频源码
			mediaRecorder.setVideoSize(height,width);//设置要捕获的视频的宽度和高度

//			switch (result){//后置摄像头调用
//				case 0:result = 180;break;
//				case 180:result = 0;break;
//			}


			mediaRecorder.setOrientationHint(result);//设置输出的视频播放的方向提示
			mediaRecorder.setVideoFrameRate(30);//设置要捕获的视频的帧速率.必须先调用setvideosource()方法.
			mediaRecorder.setVideoEncodingBitRate(3*800*800);//设置视频编码比特率
			mediaRecorder.setOutputFile(myRecAudioFile.getAbsolutePath());//设置输出文件
			mediaRecorder.prepare();//准备开始捕获和编码数据记录器,必须在start()方法之前调用
			mediaRecorder.start();
		} catch (IOException e) {
			e.printStackTrace();

		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {//屏幕触摸事件
		if (event.getAction() == MotionEvent.ACTION_DOWN) {//按下时自动对焦
			mCamera.autoFocus(myAutoFocusCallback);
		}
		return true;
	}
}
